from flask import Flask,request
from flask_cors import CORS
from app.config import Config
from app.src.base import base_bp
from app.src.auth import auth_bp
from app.src.user import user_bp
from app.src.exhibition import exhibition_bp
from app.utils.logger import setup_logger
from app.src.operation import operation_bp
from app.src.test import test_bp

def create_app():
    app = Flask(__name__)
    
    CORS(app, resources={
        r"/api/*": {
            "origins": "*",
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"],
            "allow_headers": [
                "Content-Type",
                "Authorization",
                "X-Requested-With",
                "Accept",
                "Origin",
                "Access-Control-Allow-Origin",
                "Access-Control-Allow-Headers"
            ],
            "expose_headers": ["Authorization"],
            "supports_credentials": True,
            "max_age": 600
        }
    })

    @app.before_request
    def handle_preflight():
        if request.method == "OPTIONS":
            response = app.make_default_options_response()
            return response

    app.config.from_object(Config)

    # 设置日志
    logger = setup_logger('exhibition')
    app.logger.handlers = logger.handlers

    app.logger.setLevel(logger.level)

    # 注册蓝图
    app.register_blueprint(base_bp, url_prefix='/api/base')
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    app.register_blueprint(user_bp, url_prefix='/api/user')
    app.register_blueprint(exhibition_bp, url_prefix='/api/exhibition')
    app.register_blueprint(operation_bp, url_prefix='/api/operation')
    app.register_blueprint(test_bp, url_prefix='/api/test')

    return app